import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {User} from './user';
import {AuthService} from './auth.service';
import {Router} from '@angular/router';

@Injectable()
export class UserService {
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'user/login';  // URL to web api
  token: string;
  account: string;
  private user: User = null;

  constructor(private http: Http, private authService: AuthService, private router: Router) {
  }


  // 登陆
  login(account: string, password: string): Promise<[boolean, any]> {
    const request = JSON.stringify({
      account: account,
      password: password
    });
    this.account = account;
    const requestBody = 'json=' + request;
    // 修改Content-Type
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(res => {
        const body = res.json();
        if (body.status === 1) {
          // 获取用户及权限信息
          this.user = new User();
          this.authService.setTokenId(body.token, this.account);
          this.authService.sendLoginStatus(true);
          this.token = body.token;
          return [true, body];
        } else {
          console.error('请求失败：' + body.msg);
          return [false, body.msg];
        }
      })
      .catch(this.handleError);
  }

  getToken() {
    return this.token;
  }

  getAccount() {
    return this.account;
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
